package com.ruoyi.web.controller.admin.question;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.entity.QnnQuestionnaire;
import com.ruoyi.system.service.QnnQuestionnaireService;
import com.ruoyi.system.vo.QuestionnaireVO;
import com.ruoyi.system.vo.SubmitAnswerVO;
import com.ruoyi.system.dto.QuestionnaireQueryDTO;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/questionnaire")
public class QnnQuestionnaireController {

    @Autowired
    private QnnQuestionnaireService questionnaireService;

    /**
     * 创建问卷
     */
    @PostMapping
    public AjaxResult createQuestionnaire(@RequestBody QuestionnaireVO questionnaireVO) {
        Long id = questionnaireService.createQuestionnaire(questionnaireVO);
        return AjaxResult.success(id);
    }

    /**
     * 更新问卷
     */
    @PutMapping
    public AjaxResult updateQuestionnaire(@RequestBody QuestionnaireVO questionnaireVO) {
        boolean success = questionnaireService.updateQuestionnaire(questionnaireVO);
        return AjaxResult.success(success);
    }

    /**
     * 获取问卷详情
     */
    @GetMapping("/{id}")
    public AjaxResult getQuestionnaireDetail(@PathVariable Long id) {
        QnnQuestionnaire questionnaire = questionnaireService.getQuestionnaireDetail(id);
        return AjaxResult.success(questionnaire);
    }

    /**
     * 发布问卷
     */
    @PostMapping("/publish/{id}")
    public AjaxResult publishQuestionnaire(@PathVariable Long id) {
        boolean success = questionnaireService.publishQuestionnaire(id);
        return AjaxResult.success(success);
    }

    /**
     * 结束问卷
     */
    @PostMapping("/end/{id}")
    public AjaxResult endQuestionnaire(@PathVariable Long id) {
        boolean success = questionnaireService.endQuestionnaire(id);
        return AjaxResult.success(success);
    }

    /**
     * 提交问卷答案
     */
    @PostMapping("/answer/submit")
    public AjaxResult submitAnswer(@RequestBody SubmitAnswerVO submitAnswerVO) {
        Long answerSheetId = questionnaireService.submitAnswer(submitAnswerVO);
        return AjaxResult.success(answerSheetId);
    }

    /**
     * 后台多条件查询问卷列表
     */
    @PostMapping("/query")
    public AjaxResult queryQuestionnaires(@RequestBody QuestionnaireQueryDTO dto) {
        long total = questionnaireService.queryAdminCount(dto);
        Map<String, Object> data = new HashMap<>();
        data.put("rows", questionnaireService.queryAdminList(dto));
        data.put("total", total);
        data.put("page", dto.getPage());
        data.put("size", dto.getSize());
        return AjaxResult.success(data);
    }
}
